package com.dwyinyuan.task;

import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class DownloadTask implements Runnable {

    private static String path = "D:\\practice\\spider-img\\";
    private String src;
    private String name;

    public DownloadTask(String src) {
        this.src = src;
        int n = src.lastIndexOf("/");
        this.name = src.substring(++n);
    }

    @Override
    public void run() {
        Response res = null;
        try {
            res = Jsoup.connect(src).ignoreContentType(true)
                    .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0")
                    .timeout(100000)
                    .maxBodySize(0)
                    .execute();
            byte[] bytes = res.bodyAsBytes();
            File file = new File(path + name);
            if (!file.exists()) {
                RandomAccessFile raf = new RandomAccessFile(file, "rw");
                raf.write(bytes);
                raf.close();
            }
            System.out.println(src + " 下载完成----");

        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

}
